package com.example.learn01.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.learn01.entity.User;
import com.example.learn01.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {
    //  转换成静态变量
    private static IUserService stateiuserService;
    @Resource
    private  IUserService iUserService;
    // 调用
    @PostConstruct
    public  void  setiUserService(){
        stateiuserService =iUserService;
    }

    public static  String genToken(String userId,String sign){
        String token=JWT.create().withAudience(userId) // 将 user id 保存到 token 里面
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //五分钟后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
        return token;

    }
/**
 * 获取当前用户信息
 * @return user
 * */
    public static User getCurrentUser(){
        try {
            HttpServletRequest request=  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)){
                String userId=JWT.decode(token).getAudience().get(0);
                //  静态方法只能调用静态变量
                return stateiuserService.getById((Integer.valueOf(userId)));
            }
            return null;
        }catch (Exception e){
            return  null;
        }

    }
}
